<template>
  <section class="space-y-4 pb-16">
    <!-- 筛选条件区域 - 参考Sites.vue清晰架构 -->
    <div class="bg-white rounded-2xl p-4 shadow-sm border border-gray-100">
      <!-- 时间筛选 -->
      <div class="space-y-3">
        <!-- 范围时间选择 -->
        <div class="grid grid-cols-2 gap-2">
          <input type="date" v-model="startDate"
                 @change="handleDateChange"
                 :min="minDate" :max="maxDate"
                 placeholder="开始日期"
                 class="px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
          <input type="date" v-model="endDate"
                 @change="handleDateChange"
                 :min="minDate" :max="maxDate"
                 placeholder="结束日期"
                 class="px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
        </div>

        <!-- 快捷时间选项 -->
        <div class="flex gap-1">
          <button v-for="option in quickOptions" :key="option.value"
                  @click="selectQuickOption(option.value)"
                  :class="[
                    'px-3 py-1.5 rounded text-sm font-medium transition-all whitespace-nowrap flex-1',
                    quickTime === option.value
                      ? 'bg-brand-500 text-white border border-brand-500'
                      : 'bg-gray-50 text-gray-600 hover:bg-gray-100 border border-gray-200'
                  ]">
            {{ option.label }}
          </button>
        </div>
      </div>

      <!-- 状态筛选 - 参考Sites.vue的字典筛选模式 -->
      <div class="flex items-center justify-between mt-4 pt-4 border-t border-gray-100">
        <div class="text-sm font-medium text-gray-700">状态筛选</div>
        <div class="relative">
          <button @click="showStatusPicker = !showStatusPicker"
                  class="inline-flex items-center gap-1 px-3 py-1.5 border border-gray-200 bg-white rounded-md text-sm text-gray-700 hover:bg-gray-50 shadow-sm">
            <span class="truncate max-w-[180px]">{{ selectedStatusLabel }}</span>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-4 h-4 text-gray-500"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 9l6 6 6-6"/></svg>
          </button>
          <!-- 状态下拉选择 -->
          <div v-if="showStatusPicker" class="absolute right-0 top-full mt-2 z-20 rounded-lg bg-white text-gray-900 shadow-lg ring-1 ring-black/5 overflow-hidden">
            <button v-for="opt in statusOptions" :key="opt.value" class="block w-full text-left px-3 py-2 hover:bg-gray-50 text-sm whitespace-nowrap" @click="selectStatus(opt.value)">
              <span class="truncate max-w-[16rem]">{{ opt.label }}</span>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white rounded-2xl p-5 shadow-glass">
      <div class="text-center">
        <div class="text-sm text-white/80 mb-1">累计提现</div>
        <div class="text-3xl font-bold">¥ {{ totalWithdraw.toFixed(2) }}</div>
        <div class="text-xs text-white/70 mt-1">共 {{ displayRecords.length }} 笔提现</div>
      </div>
    </div>

    <!-- 记录数量统计 -->
    <div class="flex justify-between items-center">
      <div class="text-sm text-gray-500">筛选结果</div>
      <div class="text-sm text-gray-500">共 {{ displayRecords.length }} 条记录</div>
    </div>

    <!-- 记录列表 -->
    <div class="space-y-3">

      <div v-for="record in displayRecords" :key="record.id" class="bg-white rounded-2xl p-4 shadow-sm border border-gray-100">
        <div class="flex items-center justify-between mb-3">
          <div class="flex items-center gap-3">
            <div :class="getStatusColor(record.status)" class="w-10 h-10 rounded-full flex items-center justify-center">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 text-white">
                <path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm-.53 14.03a.75.75 0 0 0 1.06 0l3-3a.75.75 0 1 0-1.06-1.06l-1.72 1.72V8.25a.75.75 0 0 0-1.5 0v5.69l-1.72-1.72a.75.75 0 0 0-1.06 1.06l3 3Z" clip-rule="evenodd"/>
              </svg>
            </div>
            <div>
              <div class="font-medium text-gray-900">{{ record.bankName }}</div>
              <div class="text-xs text-gray-500">{{ record.applyTime }}</div>
            </div>
          </div>
          <div class="text-right">
            <div class="text-lg font-semibold" :class="getAmountColor(record.status)">-¥{{ record.amount }}</div>
            <div class="text-xs" :class="getStatusTextColor(record.status)">{{ record.statusText }}</div>
          </div>
        </div>

        <!-- 待审核状态信息 -->
        <div v-if="record.status === 'processing' && record.statusText === '待审核'" class="bg-yellow-50 rounded-lg p-3">
          <div class="flex items-center justify-between text-sm">
            <span class="text-yellow-700">{{ record.withdrawMessage }}</span>
          </div>
        </div>

        <!-- 审核失败状态信息 -->
        <div v-if="record.status === 'failed' && record.statusText === '审核失败'" class="bg-red-50 rounded-lg p-3">
          <div class="flex items-center justify-between text-sm">
            <span class="text-red-700">{{ record.withdrawMessage }}</span>
          </div>
        </div>

        <!-- 待打款状态信息 -->
        <div v-if="record.status === 'processing' && record.statusText === '审核通过'" class="bg-blue-50 rounded-lg p-3">
          <div class="flex items-center justify-between text-sm">
            <span class="text-blue-700">{{ record.withdrawMessage }}</span>
          </div>
        </div>

        <!-- 打款成功状态信息 -->
        <div v-if="record.status === 'success' && record.statusText === '打款成功'" class="bg-green-50 rounded-lg p-3">
          <div class="flex items-center justify-between text-sm">
            <span class="text-green-700">{{ record.withdrawMessage }}</span>
          </div>
        </div>

        <div class="text-xs text-gray-600 bg-gray-50 rounded-lg p-2 mt-2">
          <div class="flex justify-between">
            <span>提现单号：</span>
            <span class="font-mono">{{ record.withdrawNo }}</span>
          </div>
          <div class="flex justify-between mt-1">
            <span>处理人：</span>
            <span class="font-medium">{{ record.processor || '系统自动处理' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div class="text-center py-4">
      <button v-if="hasMore" @click="loadMore" class="text-sm text-gray-600 hover:text-gray-900 px-4 py-2 border border-gray-200 rounded-lg hover:border-gray-300 transition-colors">
        加载更多记录
      </button>
      <div v-else class="text-sm text-gray-500">没有更多记录了</div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { getWithdrawRecords } from '../api/my'
import { getDictLabel, getDictOptions } from '../utils/dictionary'

const router = useRouter()

// 提现记录数据
const withdrawRecords = ref([])
const isLoading = ref(false)
const loadError = ref('')
const hasMore = ref(true)

// 筛选条件 - 参考Sites.vue清晰架构
const startDate = ref('')
const endDate = ref('')
const quickTime = ref('month')
const filterStatus = ref('all')
const showStatusPicker = ref(false)

// 快捷时间选项
const quickOptions = [
  { label: '本月', value: 'month' },
  { label: '本季度', value: 'quarter' },
  { label: '本年', value: 'year' },
  { label: '全部', value: 'all' }
]

// 使用字典数据生成状态选项 - 参考Sites.vue的实现
const statusOptions = computed(() => {
  const dictOptions = getDictOptions('提现状态') || getDictOptions('交易状态')
  const options = [
    { value: 'all', label: '全部状态' }
  ]

  if (dictOptions && dictOptions.length > 0) {
    console.log('✅ 成功获取提现状态字典选项:', dictOptions)
    dictOptions.forEach(option => {
      options.push({
        value: option.value,
        label: option.label
      })
    })
  } else {
    console.warn('❌ 提现状态字典数据未加载，状态筛选将使用默认选项')
    // 添加默认状态选项作为备选
    options.push(
      { value: '0', label: '待审核' },
      { value: '1', label: '审核失败' },
      { value: '2', label: '待打款' },
      { value: '3', label: '打款成功' }
    )
  }

  return options
})

const selectedStatusLabel = computed(() => {
  if (filterStatus.value === 'all') return '全部状态'

  // 从字典获取标签，如果获取不到则使用默认映射
  const dictLabel = getDictLabel('提现状态', filterStatus.value) ||
                   getDictLabel('交易状态', filterStatus.value)

  if (dictLabel) {
    return dictLabel
  }

  // 默认映射
  const defaultMapping = {
    '0': '待审核',
    '1': '审核失败',
    '2': '待打款',
    '3': '打款成功'
  }

  return defaultMapping[filterStatus.value] || '未知状态'
})

// 日期范围限制
const minDate = computed(() => {
  const date = new Date()
  date.setFullYear(date.getFullYear() - 1)
  return date.toISOString().split('T')[0]
})

const maxDate = computed(() => new Date().toISOString().split('T')[0])

// 计算总提现金额
const totalWithdraw = computed(() => {
  return displayRecords.value.reduce((sum, record) => sum + record.amount, 0)
})

// 显示提现记录（使用API格式化后的数据）
const displayRecords = computed(() => {
  return withdrawRecords.value?.list || []
})

// 状态选择 - 参考Sites.vue的简洁实现
const selectStatus = (value) => {
  filterStatus.value = value
  showStatusPicker.value = false
  loadWithdrawRecords(false)
}

// 快捷时间选择
const selectQuickOption = (value) => {
  quickTime.value = value

  const today = new Date()
  switch (value) {
    case 'month':
      startDate.value = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0]
      endDate.value = new Date(today.getFullYear(), today.getMonth() + 1, 0).toISOString().split('T')[0]
      break
    case 'quarter':
      const quarter = Math.floor(today.getMonth() / 3)
      startDate.value = new Date(today.getFullYear(), quarter * 3, 1).toISOString().split('T')[0]
      endDate.value = new Date(today.getFullYear(), quarter * 3 + 3, 0).toISOString().split('T')[0]
      break
    case 'year':
      startDate.value = new Date(today.getFullYear(), 0, 1).toISOString().split('T')[0]
      endDate.value = new Date(today.getFullYear(), 11, 31).toISOString().split('T')[0]
      break
    case 'all':
      startDate.value = '2025-01-01'
      endDate.value = today.toISOString().split('T')[0]
      break
  }

  loadWithdrawRecords()
}

// 处理日期变化
const handleDateChange = () => {
  quickTime.value = ''
  if (startDate.value && endDate.value) {
    loadWithdrawRecords()
  }
}

// 加载更多数据
const loadMore = () => {
  loadWithdrawRecords(true)
}

// 点击外部区域关闭下拉菜单 - 参考Sites.vue的实现
const closePickerOnOutsideClick = (event) => {
  const pickerElement = event.target.closest('.relative')
  if (!pickerElement && showStatusPicker.value) {
    showStatusPicker.value = false
  }
}

// 状态颜色映射 - 适配前端处理后的状态值
const getStatusColor = (status) => {
  console.log('🎨 getStatusColor 被调用，status:', status, '类型:', typeof status)
  const colors = {
    'processing': 'bg-yellow-500', // 处理中 - 黄色
    'failed': 'bg-red-500',        // 失败 - 红色
    'success': 'bg-green-500'      // 成功 - 绿色
  }
  const result = colors[status] || 'bg-gray-500'
  console.log('🎨 getStatusColor 返回结果:', result)
  return result
}

const getAmountColor = (status) => {
  console.log('🎨 getAmountColor 被调用，status:', status)
  const colors = {
    'processing': 'text-yellow-600', // 处理中 - 黄色
    'failed': 'text-red-600',        // 失败 - 红色
    'success': 'text-gray-900'       // 成功 - 黑色
  }
  const result = colors[status] || 'text-gray-600'
  console.log('🎨 getAmountColor 返回结果:', result)
  return result
}

const getStatusTextColor = (status) => {
  console.log('🎨 getStatusTextColor 被调用，status:', status)
  const colors = {
    'processing': 'text-yellow-600', // 处理中 - 黄色
    'failed': 'text-red-600',        // 失败 - 红色
    'success': 'text-green-600'      // 成功 - 绿色
  }
  const result = colors[status] || 'text-gray-600'
  console.log('🎨 getStatusTextColor 返回结果:', result)
  return result
}

// 加载提现记录数据 - 参考Sites.vue的防重复调用机制
let isLoadInProgress = false
const loadWithdrawRecords = async (isLoadMore = false) => {
  // 防止重复调用
  if (isLoadInProgress) {
    console.log('🔄 加载已在进行中，跳过重复调用')
    return
  }

  try {
    isLoadInProgress = true
    isLoading.value = true
    loadError.value = ''

    console.log('🚀 开始加载提现记录...', isLoadMore ? '加载更多' : '首次加载')

    // 构建请求参数 - 直接使用后端状态值，避免复杂的映射
    const params = {
      startTime: startDate.value,
      endTime: endDate.value,
      tradeStatus: filterStatus.value !== 'all' ? filterStatus.value : ''
    }

    // 加载更多时，添加lastId参数
    if (isLoadMore) {
      const currentList = withdrawRecords.value?.list || []
      if (currentList.length > 0) {
        // 获取最后一条记录的ID作为lastId
        const lastRecord = currentList[currentList.length - 1]
        params.lastId = lastRecord.id
      }
    }

    // 加载更多时，添加lastId参数
    if (isLoadMore) {
      const currentList = withdrawRecords.value?.list || []
      if (currentList.length > 0) {
        // 获取最后一条记录的ID作为lastId
        const lastRecord = currentList[currentList.length - 1]
        params.lastId = lastRecord.id
      }
    }

    console.log('📋 请求参数:', params)

    const response = await getWithdrawRecords(params)
    console.log('📡 接口响应:', response)

      if (response.success) {
        // 直接使用API层处理后的数据，不再重复处理
        console.log('🔍 API层处理后的数据:', response.data)

        if (isLoadMore) {
          // 加载更多时，追加数据
          withdrawRecords.value = {
            ...response.data,
            list: [...(withdrawRecords.value?.list || []), ...(response.data?.list || [])]
          }
        } else {
          // 首次加载时，替换数据
          withdrawRecords.value = response.data
        }

        // 判断是否还有更多数据
        hasMore.value = (response.data?.list?.length || 0) > 0

      console.log('✅ 提现记录加载成功，共', withdrawRecords.value.length, '条记录')
    } else {
      const errorMsg = response.message || '请求失败，请检查网络连接'
      loadError.value = errorMsg
      console.error('❌ 加载提现记录失败:', errorMsg)
      if (!isLoadMore) {
        withdrawRecords.value = []
      }
    }
  } catch (error) {
    const errorMsg = error.message || '网络错误，请检查连接'
    loadError.value = errorMsg
    console.error('❌ 加载提现记录异常:', error)
    if (!isLoadMore) {
      withdrawRecords.value = []
    }
  } finally {
    isLoading.value = false
    isLoadInProgress = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  console.log('🎯 WithdrawRecords组件挂载，开始加载数据')
  document.addEventListener('click', closePickerOnOutsideClick)

  // 设置默认日期为本月
  const today = new Date()
  startDate.value = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0]
  endDate.value = new Date(today.getFullYear(), today.getMonth() + 1, 0).toISOString().split('T')[0]

  loadWithdrawRecords()
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closePickerOnOutsideClick)
})
</script>
